package psn.zjk.common.algorithm.maxNum;

/**
 * @USER white
 * @DATETIME 2021/1/9 10:01
 */

import java.util.*;
import java.util.stream.Collectors;

public class Solution {
    /**
     * 最大数
     *
     * @param nums int整型一维数组
     * @return string字符串
     */
    public String solve(int[] nums) {
        if (nums == null || nums.length == 0) {
            return "";
        }
        if (Arrays.stream(nums).sum() == 0) {
            return "0";
        }
        List<Integer> sortedNums = Arrays.stream(nums).boxed().collect(Collectors.toList());
        sortedNums.sort((o1, o2) -> {
            int i = 0;
            LinkedList<Integer> l1 = convert(o1);
            LinkedList<Integer> l2 = convert(o2);
            while (true) {
                if (l1.size() > i && l2.size() > i) {
                    Integer x = l1.get(i);
                    Integer y = l2.get(i);
                    if (x == y) {
                        i++;
                        continue;
                    } else {
                        return y - x;
                    }
                } else {
                    //因为需要降序，所以要反着减！！！
                    return l2.getLast() - l1.getLast();
                }
            }
        });
        StringBuilder sb = new StringBuilder();
        for (int z : sortedNums) {
            sb.append(z);
        }
        return sb.toString();
    }


    private LinkedList<Integer> convert(int num) {
        LinkedList<Integer> l1 = new LinkedList<>();
        l1.add(num % 10);
        while (num > 9) {
            num /= 10;
            l1.addFirst(num % 10);
        }
        return l1;
    }

    public static void main(String[] args) {
        int[] z = {1, 2, 3, 4, 5};
//        List<Integer> collect = Arrays.stream(z).mapToObj(value -> Integer.valueOf(value)).collect(Collectors.toList());
//        collect.sort(new X());
        String solve = new Solution().solve(z);
        System.out.println(solve);
    }

    static class X implements Comparator<Integer> {
        @Override
        public int compare(Integer x, Integer y) {
//            x是后面的元素，y是前面的
            System.out.println(x);
            System.out.println(y);
            System.out.println("=================");
            //x-y是升序
            return x-y;
            //y-x是降序
        }
    }
}